﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Ionic.Zip;
using MethodWorx.CMS.Membership;

namespace MethodWorx.CMS.TemplateParser.Installer
{
    public class InstallerEngine
    {
        private Stream stream;
        private Dictionary<string, byte[]> files;
        private User user;

        public InstallerEngine(string filename, Stream stream, User user)
        {
            if(stream == null)
                throw new ArgumentNullException("stream");

            this.stream = stream;
            this.Filename = filename;
            this.user = user;

            this.ReadZipFile(stream);
        }

        public string Filename { get; private set; }

        private void ReadZipFile(Stream stream)
        {
            using (var zip = ZipFile.Read(stream))
            {
                files = new Dictionary<string, byte[]>();
                foreach (var entry in zip.Entries)
                {
                     using (MemoryStream ms = new MemoryStream())
                    {
                        entry.Extract(ms);

                        ms.Seek(0, SeekOrigin.Begin);
                        byte[] zipBuffer = new byte[ms.Length];
                        ms.Read(zipBuffer, 0, zipBuffer.Length);

                        files.Add(entry.FileName.ToLower(), zipBuffer);
                    }
                    
                }

                this.Files = files.Keys;
            }
        }

        public IEnumerable<string> Files { get; private set; }

        public InstallerParser GetParser()
        {
            var installerParser = new InstallerParser(this.files, this.user);
            return installerParser;
        }
    }
}
